/* Copyright (c) 2004-2022 peigen.info. All rights reserved. */

package info.peigen.hotpot.common.core.domain.bank;

import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.core.annotation.Comment;
import jakarta.validation.constraints.Max;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import lombok.experimental.SuperBuilder;

/**
 * <b>(SwiftCode)</b>
 * Example of a SWIFT code
 * AAAA(Bank code) + BB(Country code) + CC(Location code) + 123(Branch code)
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/9/17
 */
@SuperBuilder
@Data
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
public class SwiftCode {
    public final static int SWIFT_CODE_LENGTH_LIMIT = 8;
    @Comment(value = "bankCode")
    @Max(4)
    String bankCode;
    @Comment(value = "countryCode")
    @Max(2)
    String countryCode;
    @Comment(value = "locationCode")
    @Max(2)
    String locationCode;
    @Comment(value = "branchCode")
    @Max(3)
    String branchCode;

    public static SwiftCode create(String swiftCode) {
        if (StrUtil.length(swiftCode) < SWIFT_CODE_LENGTH_LIMIT) {
            throw new IllegalArgumentException("swiftCode=[" + swiftCode + "]位数小于8");
        }
        switch (swiftCode.length()) {
            case 8:
                return SwiftCode.builder()
                        .bankCode(StrUtil.subPre(swiftCode, 4))
                        .countryCode(StrUtil.subWithLength(swiftCode, 4, 2))
                        .locationCode(StrUtil.subWithLength(swiftCode, 6, 2))
                        .branchCode("XXX")
                        .build();
            case 11:
                return SwiftCode.builder()
                        .bankCode(StrUtil.subPre(swiftCode, 4))
                        .countryCode(StrUtil.subWithLength(swiftCode, 4, 2))
                        .locationCode(StrUtil.subWithLength(swiftCode, 6, 2))
                        .branchCode(StrUtil.subSufByLength(swiftCode, 3))
                        .build();
            default:
                return null;
        }
    }

    public String getSwiftCode() {
        return this.bankCode + this.countryCode + this.locationCode + this.branchCode;
    }


}